package net.wanho.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import net.wanho.constant.RoleConstant;
import net.wanho.constant.UserConstant;
import net.wanho.dto.AddRoleDTO;
import net.wanho.dto.RoleAuthDTO;
import net.wanho.dto.RoleDTO;
import net.wanho.mapper.RoleAuthMapper;
import net.wanho.mapper.UserInfoMapper;
import net.wanho.po.Role;
import net.wanho.po.RoleAuth;
import net.wanho.po.UserInfo;
import net.wanho.service.RoleService;
import net.wanho.mapper.RoleMapper;
import net.wanho.util.ThreadUtil;
import net.wanho.vo.ExportRoleVo;
import net.wanho.vo.ExportVo;
import net.wanho.vo.PageInfo;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【role(角色表)】的数据库操作Service实现
* @createDate 2025-04-28 11:41:58
*/
@Service
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
    implements RoleService{
    private final RoleMapper roleMapper;

    private final RoleAuthMapper roleAuthMapper;

    private final UserInfoMapper userInfoMapper;

    private final RedisTemplate<String, Object> redisTemplate;
    @Override
    public List<Role> selectByUserId(Integer id) {
        // 获取用户已分配的角色
        List<Role> roles = roleMapper.findByUserID(id);
        // 设置角色状态为启用
        roles.forEach(role -> role.setRoleState("1"));
        return roles;
    }

    @Override
    public PageInfo<Role> rolePageList(Integer pageNum, Integer pageSize, RoleDTO roleDTO) {
        Page <Role> page = new Page<>(pageNum,pageSize);

        QueryWrapper <Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(!ObjectUtil.isEmpty(roleDTO.getRoleName()), "role_name", roleDTO.getRoleName());
        queryWrapper.eq(!ObjectUtil.isEmpty(roleDTO.getRoleCode()), "role_code", roleDTO.getRoleCode());
        queryWrapper.eq(!ObjectUtil.isEmpty(roleDTO.getRoleState()), "role_state", roleDTO.getRoleState());

        Page<Role> p = this.baseMapper.selectByPage(page, queryWrapper);

        PageInfo <Role> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page.getCurrent());
        pageInfo.setPageSize(page.getSize());
        pageInfo.setTotalNum(page.getTotal());
        pageInfo.setPageCount(page.getPages());
        pageInfo.setLimitIndex(page.offset());
        pageInfo.setResultList(p.getRecords());
        return pageInfo;
    }

    @Override
    public void addRole(AddRoleDTO addRoleDTO) {
        // 角色名唯一
        Role roleName = this.getOne(new QueryWrapper<Role>().eq("role_name", addRoleDTO.getRoleName()));// 角色名唯一
        if (ObjectUtil.isNotEmpty(roleName)) {
            throw new RuntimeException("角色名已存在");
        }
        Role role = new Role();
        BeanUtils.copyProperties(addRoleDTO, role);
        LocalDateTime now = LocalDateTime.now();
        role.setCreateTime(now);
        Integer id = ThreadUtil.getId();
        role.setCreateBy(id);
        role.setRoleState(RoleConstant.enable);
        roleMapper.insert(role);
        // 分配默认权限id
        RoleAuth roleAuth = new RoleAuth();
        roleAuth.setRoleId(role.getRoleId());
        roleAuth.setAuthId(RoleConstant.defaultAuthId);
        roleAuthMapper.insert(roleAuth);
    }

    @Override
    public void updateState(Role role) {
        Integer id = ThreadUtil.getId();
        role.setUpdateBy(id);
        LocalDateTime now = LocalDateTime.now();
        role.setUpdateTime(now);
        this.updateById(role);
    }

    @Override
    public Role selectById(Integer id) {
        Role role = this.getById(id);
        Integer createBy = role.getCreateBy();
        String getCode = userInfoMapper.selectById(createBy).getUserCode();
        role.setGetCode(getCode);
        return role;
    }

    @Override
    public void modifyById(Role role) {
        LocalDateTime  now = LocalDateTime.now();
        role.setUpdateTime(now);
        Integer id = ThreadUtil.getId();
        role.setUpdateBy(id);
        this.updateById(role);
    }

    @Override
    public void updateRoleAuth(RoleAuthDTO roleAuthDTO) {
        // 删除角色权限
        roleAuthMapper.delete(new QueryWrapper<RoleAuth>().eq("role_id", roleAuthDTO.getRoleId()));
        // 添加角色权限
        List<Integer> authIds = roleAuthDTO.getAuthIds();
        List<RoleAuth> collect = authIds.stream().map(authId -> {
            RoleAuth roleAuth = new RoleAuth();
            roleAuth.setRoleId(roleAuthDTO.getRoleId());
            roleAuth.setAuthId(authId);
            return roleAuth;
        }).collect(Collectors.toList());
        roleAuthMapper.insertBatch(collect);
        // 更改角色的权限后，需要删除Redis中缓存的所有菜单数据！！
        redisTemplate.delete(UserConstant.MENU_PREFIX);
    }



    //@Override
    //public List<Role> getAllRoles() {
    //    return this.list();
    //}
}




